<template>
  <div class="dashboard-page">
    <h1 class="page-title">控制面板</h1>
    
    <!-- 统计卡片 -->
    <div class="stat-cards">
      <a-card class="stat-card">
        <template #title>
          <span class="card-title"><file-text-outlined /> 新闻总数</span>
        </template>
        <div class="stat-value">{{ stats.totalNews }}</div>
        <div class="stat-desc">全部新闻文章数量</div>
      </a-card>
      
      <a-card class="stat-card">
        <template #title>
          <span class="card-title"><eye-outlined /> 总浏览量</span>
        </template>
        <div class="stat-value">{{ stats.totalViews }}</div>
        <div class="stat-desc">所有新闻的总浏览次数</div>
      </a-card>
      
      <a-card class="stat-card">
        <template #title>
          <span class="card-title"><calendar-outlined /> 本月发布</span>
        </template>
        <div class="stat-value">{{ stats.monthlyNews }}</div>
        <div class="stat-desc">本月发布的新闻数量</div>
      </a-card>
      
      <a-card class="stat-card">
        <template #title>
          <span class="card-title"><notification-outlined /> 通知公告</span>
        </template>
        <div class="stat-value">{{ stats.totalNotices }}</div>
        <div class="stat-desc">已发布的通知公告数量</div>
      </a-card>
    </div>
    
    <!-- 分类统计 -->
    <div class="chart-section">
      <a-card title="新闻分类统计" class="chart-card">
        <div class="chart-container" ref="categoryChartRef"></div>
      </a-card>
      
      <a-card title="近30天发布趋势" class="chart-card">
        <div class="chart-container" ref="trendChartRef"></div>
      </a-card>
    </div>
    
    <!-- 最近发布的新闻 -->
    <a-card title="最近发布的新闻" class="recent-news-card">
      <a-table
        :columns="columns"
        :data-source="recentNews"
        :pagination="false"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <a @click="viewNews(record.id)">{{ record.title }}</a>
          </template>
          <template v-else-if="column.key === 'category'">
            <a-tag :color="getCategoryColor(record.category)">
              {{ getCategoryName(record.category) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'publishTime'">
            {{ formatDate(record.publishTime) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editNews(record.id)">
                <template #icon><edit-outlined /></template>
                编辑
              </a-button>
              <a-button type="link" size="small" @click="viewNews(record.id)">
                <template #icon><eye-outlined /></template>
                查看
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
      
      <div class="view-all-btn">
        <a-button type="primary" @click="goToNewsManagement">查看全部新闻</a-button>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  FileTextOutlined,
  EyeOutlined,
  CalendarOutlined,
  NotificationOutlined,
  EditOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

const router = useRouter()
const loading = ref(false)

// 图表引用
const categoryChartRef = ref(null)
const trendChartRef = ref(null)
let categoryChart = null
let trendChart = null

// 统计数据
const stats = ref({
  totalNews: 0,
  totalViews: 0,
  monthlyNews: 0,
  totalNotices: 0
})

// 最近发布的新闻
const recentNews = ref([])

// 表格列定义
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
    width: '40%'
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: '15%'
  },
  {
    title: '作者',
    dataIndex: 'author',
    key: 'author',
    width: '15%'
  },
  {
    title: '发布时间',
    dataIndex: 'publishTime',
    key: 'publishTime',
    width: '15%'
  },
  {
    title: '操作',
    key: 'action',
    width: '15%'
  }
]

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取分类名称
const getCategoryName = (category) => {
  const categoryMap = {
    'important': '学校要闻',
    'academic': '学术动态',
    'general': '综合新闻',
    'notice': '通知公告'
  }
  return categoryMap[category] || '未分类'
}

// 获取分类颜色
const getCategoryColor = (category) => {
  const colorMap = {
    'important': 'blue',
    'academic': 'green',
    'general': 'purple',
    'notice': 'orange'
  }
  return colorMap[category] || 'default'
}

// 初始化分类统计图表
const initCategoryChart = () => {
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['学校要闻', '学术动态', '综合新闻', '通知公告']
      },
      series: [
        {
          name: '新闻分类',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 35, name: '学校要闻' },
            { value: 28, name: '学术动态' },
            { value: 22, name: '综合新闻' },
            { value: 15, name: '通知公告' }
          ]
        }
      ]
    }
    
    categoryChart.setOption(option)
  }
}

// 初始化发布趋势图表
const initTrendChart = () => {
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
    
    // 生成最近30天的日期
    const dates = []
    for (let i = 29; i >= 0; i--) {
      const date = dayjs().subtract(i, 'day').format('MM-DD')
      dates.push(date)
    }
    
    // 模拟数据
    const data = dates.map(() => Math.floor(Math.random() * 5))
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: dates,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            interval: 4,
            rotate: 30
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '发布数量',
          type: 'bar',
          barWidth: '60%',
          data: data
        }
      ]
    }
    
    trendChart.setOption(option)
  }
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    // 实际项目中应该调用API
    // const response = await axios.get('/api/admin/dashboard')
    // const data = response.data
    // stats.value = data.stats
    // recentNews.value = data.recentNews
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟统计数据
    stats.value = {
      totalNews: 127,
      totalViews: 25648,
      monthlyNews: 32,
      totalNotices: 45
    }
    
    // 模拟最近发布的新闻
    const categories = ['important', 'academic', 'general', 'notice']
    recentNews.value = Array.from({ length: 5 }, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() - i)
      
      return {
        id: 100 + i,
        title: `最近发布的新闻标题示例 ${i + 1}`,
        category: categories[Math.floor(Math.random() * categories.length)],
        author: '新闻中心',
        publishTime: date.toISOString().split('T')[0],
        viewCount: Math.floor(Math.random() * 1000) + 100
      }
    })
    
    // 初始化图表
    initCategoryChart()
    initTrendChart()
    
  } catch (error) {
    message.error('获取仪表盘数据失败，请稍后再试')
    console.error('获取仪表盘数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看新闻详情
const viewNews = (id) => {
  router.push(`/news/${id}`)
}

// 编辑新闻
const editNews = (id) => {
  router.push(`/admin/news/edit/${id}`)
}

// 跳转到新闻管理页面
const goToNewsManagement = () => {
  router.push('/admin/news')
}

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (categoryChart) categoryChart.resize()
  if (trendChart) trendChart.resize()
}

onMounted(() => {
  fetchDashboardData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (categoryChart) categoryChart.dispose()
  if (trendChart) trendChart.dispose()
})
</script>

<style scoped>
.dashboard-page {
  padding-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #003366;
}

/* 统计卡片样式 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 4px;
  overflow: hidden;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #003366;
  margin-bottom: 5px;
}

.stat-desc {
  color: #666;
  font-size: 14px;
}

/* 图表区域样式 */
.chart-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 4px;
  overflow: hidden;
}

.chart-container {
  height: 300px;
}

/* 最近发布的新闻样式 */
.recent-news-card {
  border-radius: 4px;
  overflow: hidden;
}

.view-all-btn {
  margin-top: 16px;
  text-align: center;
}

/* 响应式布局 */
@media (max-width: 992px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 576px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
}
</style>